import { InjectRedis } from '@nestjs-modules/ioredis';
import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';
import { RateLimiterMemory, RateLimiterRedis } from 'rate-limiter-flexible';

@Injectable()
export class RateLimiterService {
  rateLimiterManager: RateLimiterRedis = null
  constructor(
    @InjectRedis() private readonly redis: Redis,
  ) {
    this.rateLimiterManager = new RateLimiterRedis({
      storeClient:this.redis,
      keyPrefix: 'rateLimiterManager',
      points: 20,
      duration: 60,
      dbName: !process.env.ServerApp ? "1" : process.env.redisdb
    });
  }
  
  async consume_manager(key, number?: number, duration?: number){
    try{
      let res = await this.rateLimiterManager.consume(key, number || 1, {customDuration: duration || 1 * 60 })
      console.log(res,'----res')
      if(res){
        return true
      }else{
        return false
      }
    }catch(err){
      console.log(err,'----err')

      return false
    }
  }
}
